import {
  ContextMenu,
  MenuItem,
  MenuItemParams,
  MenuSeparator,
  IContextMenu,
  CMEVENTS,
} from '@amcax/base';
import { Picker3D, PickerMgr } from '@amcax/renderer';
import { wsApi } from '../../../../server/wsApi';
import { docMgr } from '../../../../manager/DocumentManager';
import { userEvents } from '../../../../module';

function Component(props: any) {
  function handleItemClick({
    id,
    triggerEvent,
    event,
    props,
    data,
  }: MenuItemParams<any, any>) {
    const selectedModels =
      PickerMgr.getPicker<Picker3D>('3d').getSelectedModels();

    if (id === 'addToComponentLibrary') {
      console.log('addToComponentLibrary', selectedModels);
      if (selectedModels.size > 0) {
        console.log('addToComponentLibrary[selectedModels]', selectedModels);
        const dxid = selectedModels.keys().next().value;
        console.log('addToComponentLibrary', dxid);
        userEvents.emit(CMEVENTS.COMPONENT_ADD_MODAL_SHOW, dxid);
      }
    } else if (id === 'hide') {
      for (const [key, value] of selectedModels) {
        setModelVisibility(key, false);
      }
    } else if (id === 'delete') {
      for (const [key, value] of selectedModels) {
        deleteModel(key);
      }
    }
  }

  const setModelVisibility = (dxid: string, visibility: boolean) => {
    wsApi.setVisible(dxid, visibility);
    docMgr.updateDocumentObjects();
  };
  const deleteModel = (dxid: string) => {
    wsApi.delete(dxid);
    docMgr.updateDocumentObjects();
  };

  return (
    <ContextMenu id={props.id}>
      <MenuItem
        id='addToComponentLibrary'
        onClick={handleItemClick}>
        添加到构件库
      </MenuItem>
      <MenuItem
        id='hide'
        onClick={handleItemClick}>
        隐藏
      </MenuItem>
      <MenuSeparator />
      <MenuItem
        id='delete'
        onClick={handleItemClick}>
        删除
      </MenuItem>
    </ContextMenu>
  );
}

const show = (id: string, params?: any): boolean => {
  const selectedModels =
    PickerMgr.getPicker<Picker3D>('3d').getSelectedModels();
  console.log('selectedModels', selectedModels);
  return selectedModels.size > 0;
};

export const ModelContextMenu: IContextMenu = {
  id: 'modelContextMenu',
  show,
  render: (id: string, params?: any) => (
    <Component
      id={id}
      {...params}
    />
  ),
};
